package com.infore.airsupervise.ui.widget;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.infore.airsupervise.R;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.BaseEntity;
import com.infore.airsupervise.utils.ToastUtil;

import java.util.Random;

/**
 * 带刷新/加载的Recycler View
 *
 * 此控件依赖于BaseRecyclerViewAdapterHelper库、{@link MsgConst}、{@link StatusConst}、{@link BaseEntity}、
 * {@link ToastUtil}。
 * 使用时需调用{@link #setAdapter(BaseQuickAdapter)}设置适配器、调用{@link #setActionListener(OnActionListener)}
 * 设置动作监听。
 * 提供了通用的网络请求失败和成功的处理，值得注意的是：当时用代码进行刷新操作时setRefreshing(true)，需手动调用onRefresh(),
 * swipeRecyclerView.getSwipeLayout().setRefreshing(true);
 * swipeRecyclerView.onRefresh();
 *
 * 作者: dingxinlin
 * 创建日期: 2017/4/17 16:54
 */

public class SwipeRecyclerView<T extends BaseEntity> extends FrameLayout
        implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    private Context context;

    private SwipeRefreshLayout swipeLayout;
    private RecyclerView recyclerView;
    // 无数据时填充view
    private EmptyView emptyView;

    // 适配器
    private BaseQuickAdapter<T, BaseViewHolder> adapter;
    // 动作监听接口
    private OnActionListener actionListener;


    /**
     * 动作监听接口
     */
    public interface OnActionListener {
        void onRefresh();
        void onLoadMore();
        void onItemClick(BaseQuickAdapter adapter, View view, int position);
    }


    /**
     * 构造方法
     */
    public SwipeRecyclerView(@NonNull Context context) {
        this(context, null);
    }

    public SwipeRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SwipeRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;

        View rootView = LayoutInflater.from(context).inflate(R.layout.common_refresh_recycler, this);
        swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_layout);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);

        // 设置swipeLayout
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(Color.rgb(52,152,219), Color.rgb(231,76,60), Color.rgb(46,204,113));

        // 设置recyclerView
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(new ItemDecoration1px(context, ItemDecoration1px.VERTICAL_LIST));
        recyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (null != actionListener) {
                    actionListener.onItemClick(adapter, view, position);
                }
            }
        });

        // 设置emptyView
        emptyView = new EmptyView(context);
        emptyView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                swipeLayout.setRefreshing(true);
                onRefresh();
            }
        });
    }


    /**
     * 原刷新、加载回调
     */
    @Override
    public void onRefresh() {
        if (null == actionListener) {
            return;
        }
        // 使加载不可用
        adapter.setEnableLoadMore(false);
        // 刷新操作
        actionListener.onRefresh();
    }

    @Override
    public void onLoadMoreRequested() {
        if (null == actionListener) {
            return;
        }
        // 使刷新不可用
        swipeLayout.setEnabled(false);
        // 加载操作
        actionListener.onLoadMore();
    }


    /**
     * 通用成功处理
     */
    public void commonSuccessHandle(boolean isRefresh, int pageSize) {

        if (isRefresh) {
            // 结束刷新、使加载可用
            swipeLayout.setRefreshing(false);
            adapter.setEnableLoadMore(true);

            // 无数据时显示
            if (pageSize == 0) {
                emptyView.setShowInfo(R.drawable.status_search_null, MsgConst.EMPTY_DATA);
                adapter.setEmptyView(emptyView);
            }

        } else {
            if(pageSize>=20) {
                adapter.loadMoreComplete();
            }
            // 使刷新可用
            swipeLayout.setEnabled(true);
        }
        //只要size小于20条
        if(pageSize < 20){
            adapter.loadMoreEnd();
        }
    }

    /**
     * 通用失败处理
     */
    public void commonFailedHandle(boolean isRefresh, int errorCode, String title, String desc) {

        if (isRefresh) {

            int imgRes = R.drawable.status_connect_failed;
            switch (errorCode) {
                case StatusConst.CODE_CONNECT_FAIL:
                    imgRes = R.drawable.status_connect_failed;
                    break;

                case StatusConst.CODE_CONNECT_TIMEOUT:
                    imgRes = R.drawable.status_timeout;
                    break;

                case StatusConst.CODE_SERVER_EXCEPTION:
                    imgRes = R.drawable.status_server_fix;
                    break;

                case StatusConst.CODE_OPERATION_FAIL:
                    imgRes = R.drawable.status_connect_failed;
                    break;
            }

            emptyView.setShowInfo(imgRes, title);
            adapter.setEmptyView(emptyView);

            // toast提示
            ToastUtil.showLong(context, desc);
            // 结束刷新
            swipeLayout.setRefreshing(false);

        } else {

            // 结束加载
            adapter.loadMoreFail();
        }
    }


    /**
     * 配置适配器
     */
    private void configAdapter() {
        adapter.setOnLoadMoreListener(this);
        adapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
        adapter.isFirstOnly(false);
        recyclerView.setAdapter(adapter);
    }


    /**
     * get/set方法
     */
    public SwipeRefreshLayout getSwipeLayout() {
        return swipeLayout;
    }

    public RecyclerView getRecyclerView() {
        return recyclerView;
    }

    public BaseQuickAdapter<T, BaseViewHolder> getAdapter() {
        return adapter;
    }

    public void setAdapter(BaseQuickAdapter<T, BaseViewHolder> quickAdapter) {
        this.adapter = quickAdapter;

        // 配置适配器
        configAdapter();
    }

    public void setActionListener(OnActionListener actionListener) {
        this.actionListener = actionListener;
    }
}
